/*--------------------------------------------------------------------------------------------------------------------------*/
/*!!Warning: This is a key information asset of Huawei Tech Co.,Ltd                                                         */
/*CODEMARK:kOyQZYzjDpyGdBAEC2GaWmZfTxYQ/Kw8rZS6n+Xl5a8Y99A4wNRboDw+Q2eDbcchF3Tru5p3
onyliNhfFWhvrNrqXkM+8ImNYzrnfN7/GtRq08YfDoRRqeSTuDuuKkOVYNd3RApOq+o4c0eG
dHS4o1SoF58Aivf3UgIqtLVZ1+P7Bdj1dNry670VGPAxHOeH9dxHiUTaWNqdgFOvARMhsS+3
K5F+n83f78nESOp5X5hxiXIG+n+neNHO5SlJ9ZcAOXECSJcoTLtkCkKvmQ/pYg==*/
/*--------------------------------------------------------------------------------------------------------------------------*/
package com.lituoxy.dialer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.rcs.call.CallApi;
import com.huawei.rcs.call.CallSession;
import com.huawei.rcs.log.LogApi;
import com.huawei.rcs.system.SysApi.PhoneUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 接听电话界面
 */
public class ACT_DemoCallTalking extends Activity {

    private Button btnSpeaker;
    private Button btnMute;
    private Button btnHold;
    private TextView txtPeerNumber;
    private TextView txtCallState;
    private TextView txtCallDuration;
    private TextView txtNetworkQuality;

    private Button btnVShare;
    private Button btnAcceptVShare;
    private CallSession videoShareCallsession = null;
    private boolean isVideoShareCaller = false;
    public static String PARAM_SESSION_ID = "PARAM_SESSION_ID";
    public static String PARAM_IS_CALLER = "PARAM_IS_CALLER";

    private EditText mEditAudioRecordSource;

    private AlertDialog alertDialog;

    private CallSession callSession;

    private boolean isMute = false;

    private Timer timer;
    private int callTime;
    private Handler handler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo_call_talking);

        callSession = CallApi.getForegroudCallSession();

        if (null == callSession) {
            LogApi.d("V2OIP", "ACT_DemoCallTalking onCreate: no call is talking any more.");
            finish();
            return;
        }

        initViews();
        /* register broadcast receivers. */
        registerReceivers();
        /* calculate call duration. */
        startCallTimeTask();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /* unregister broadcast receivers. */
        unRegisterReceivers();
        if (null != alertDialog) {
            alertDialog.dismiss();
            alertDialog = null;
        }
        /* end call time task.You should stop the time task when this
    	 * activity is destroy. */
        stopCallTimeTask();
    }

    private void initViews() {
        btnSpeaker = (Button) findViewById(R.id.call_btn_speaker_talking);
        btnMute = (Button) findViewById(R.id.call_btn_mute_talking);

        txtPeerNumber = (TextView) findViewById(R.id.call_txt_contact_num_talking);
        txtCallState = (TextView) findViewById(R.id.call_txt_call_state_talking);
        txtCallDuration = (TextView) findViewById(R.id.call_txt_call_time_talking);
        txtNetworkQuality = (TextView) findViewById(R.id.call_txt_qos_talking);
        btnAcceptVShare = (Button) findViewById(R.id.call_btn_accept_video_share_talking);

        mEditAudioRecordSource = (EditText) this.findViewById(R.id.audioSourceType);
    	
    	/* used by user to switch speakerphone. */
        AudioManager audioManamger = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        boolean speakerState = audioManamger.isSpeakerphoneOn();
        txtCallState.setText(speakerState ? "扬声器" : "");
        btnSpeaker.setText(speakerState ? "扬声器 关" : "扬声器 开");

        txtPeerNumber.setText(callSession.getPeer().getNumber());
    }

    private void stopCallTimeTask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void startCallTimeTask() {
        timer = new Timer();
        callTime = (int) ((System.currentTimeMillis() - callSession.getOccurDate()) / 1000);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                callTime++;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        txtCallDuration.setText(PhoneUtils.getCallDurationTime(callTime));
                    }
                });
            }
        }, 1000, 1000);
    }

    private void registerReceivers() {
    	/* Register a broadcast reciever which is used for dealing with call invitation event. */
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(
                callInvitationReciever,
                new IntentFilter(CallApi.EVENT_CALL_INVITATION));
    	/* Register a broadcast reciever which is used for detecting call status. */
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(
                callStatusChangedReceiver,
                new IntentFilter(CallApi.EVENT_CALL_STATUS_CHANGED));
    	/* Register a broadcast reciever which is used for detecting call type invite by callee. */
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(
                callTypeChangeInvitationReceiver,
                new IntentFilter(CallApi.EVENT_CALL_TYPE_CHANGED_INVITATION));
    	/* Register a broadcast reciever which is used for detecting call type. */
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(
                callTypeChangedReceiver,
                new IntentFilter(CallApi.EVENT_CALL_TYPE_CHANGED));
    	/* Register a broadcast reciever which is used for detecting call type whether it has changed into rejected. */
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(
                callTypeChangeRejectedReceiver,
                new IntentFilter(CallApi.EVENT_CALL_TYPE_CHANGED_REJECTED));
    	/* Register a broadcast reciever, in order to deal with qos report event. */
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(
                callQosReportReceiver,
                new IntentFilter(CallApi.EVENT_CALL_QOS_REPORT));
    }

    private void unRegisterReceivers() {
        LocalBroadcastManager.getInstance(getApplicationContext())
                .unregisterReceiver(callInvitationReciever);

        LocalBroadcastManager.getInstance(getApplicationContext())
                .unregisterReceiver(callStatusChangedReceiver);

        LocalBroadcastManager.getInstance(getApplicationContext())
                .unregisterReceiver(callTypeChangeInvitationReceiver);

        LocalBroadcastManager.getInstance(getApplicationContext())
                .unregisterReceiver(callTypeChangedReceiver);

        LocalBroadcastManager.getInstance(getApplicationContext())
                .unregisterReceiver(callTypeChangeRejectedReceiver);

        LocalBroadcastManager.getInstance(getApplicationContext())
                .unregisterReceiver(callQosReportReceiver);
    }

    /* accept a video share call. */
    public void onClick_acceptVideoShare(View v) {
        if (null != videoShareCallsession) {
            videoShareCallsession.acceptVideoShare();
        }
    }

    /* 是否打开扬声器 */
    public void onClick_Speaker(View v) {
        AudioManager audioManamger = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        boolean speakerState = !audioManamger.isSpeakerphoneOn();
        audioManamger.setSpeakerphoneOn(speakerState);
        txtCallState.setText(speakerState ? "扬声器：开" : "");
        btnSpeaker.setText(speakerState ? "扬声器 关" : "扬声器");
    }

    /*是否静音*/
    public void onClick_Mute(View v) {
        isMute = !isMute;

        if (isMute) {
            callSession.mute();
            txtCallState.setText("静音");
            btnMute.setText("静音 关");
        } else {
            callSession.unMute();
            txtCallState.setText("");
            btnMute.setText("静音 开");
        }
    }

    /* 挂断 */
    public void onClick_End(View v) {
        callSession.terminate();
    }

    /* received a video share call. */
    private BroadcastReceiver callInvitationReciever = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            videoShareCallsession = (CallSession) intent.getSerializableExtra(CallApi.PARAM_CALL_SESSION);
            if (null == videoShareCallsession) {
                return;
            }
			/* only received by callee. */
            if (CallSession.TYPE_VIDEO_SHARE == videoShareCallsession.getType()) {
                btnVShare.setVisibility(View.GONE);
                btnAcceptVShare.setVisibility(View.VISIBLE);
                isVideoShareCaller = false;
                Toast.makeText(ACT_DemoCallTalking.this, "A Video Share Invitation Incoming", Toast.LENGTH_LONG).show();
            }
        }
    };

    private BroadcastReceiver callStatusChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CallSession session = (CallSession) intent.getSerializableExtra(CallApi.PARAM_CALL_SESSION);
			/* The status of video share call is different from another call. */
            if (session == videoShareCallsession) {
                int newStatus = intent.getIntExtra(CallApi.PARAM_NEW_STATUS, CallSession.STATUS_IDLE);

                switch (newStatus) {
                    case CallSession.STATUS_ALERTING:
                        Toast.makeText(getApplicationContext(), "Video Share Seesion is Alerting", Toast.LENGTH_LONG).show();
                        break;
                    case CallSession.STATUS_CONNECTED:    //accept by callee
					/*Intent newIntent = new Intent(ACT_DemoCallTalking.this, ACT_DemoCallVideoSharing.class);
					newIntent.putExtra(PARAM_SESSION_ID, session.getSessionId());
					newIntent.putExtra(PARAM_IS_CALLER, isVideoShareCaller);
					startActivityForResult(newIntent, 0);*/
                        break;
                    case CallSession.STATUS_IDLE:    //reject by callee
                        if (isVideoShareCaller) {
                            Toast.makeText(getApplicationContext(), "Video Share Seesion is terminated", Toast.LENGTH_LONG).show();
                        }
                        btnAcceptVShare.setVisibility(View.GONE);
                        btnVShare.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;
                }

                return;
            }

            if (!callSession.equals(session)) {
                return;
            }
            int newStatus = intent.getIntExtra(CallApi.PARAM_NEW_STATUS, CallSession.STATUS_IDLE);
            switch (newStatus) {
                case CallSession.STATUS_HOLD:
                    txtCallState.setText("Calling hold");
                    btnHold.setText("Unhold");
                    break;
                case CallSession.STATUS_HELD:
                    txtCallState.setText("Calling held");
                    btnHold.setEnabled(false);
                    break;
                case CallSession.STATUS_CONNECTED:
                    txtCallState.setText("Calling");
                    btnHold.setText("Hold");
                    btnHold.setEnabled(true);
                    break;
                case CallSession.STATUS_IDLE://结束通话
                    ((DialerApplication) getApplication()).Calling = false;
                    finish();
                    break;
                default:
                    break;
            }
        }
    };

    /* receive a invitation to video call. */
    private BroadcastReceiver callTypeChangeInvitationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CallSession session = (CallSession) intent.getSerializableExtra(CallApi.PARAM_CALL_SESSION);
            if (!callSession.equals(session)) {
                return;
            }
            Builder dl = new AlertDialog.Builder(ACT_DemoCallTalking.this);
            dl.setTitle("Add Video Invitation");
            //dl.setMessage(R.string.fail);
            dl.setMessage("The other party is inviting a video call, accept or not?");
            dl.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    callSession.acceptAddVideo();
                    alertDialog.dismiss();
                    alertDialog = null;
                }
            });
            dl.setNegativeButton("Reject", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    callSession.rejectAddVideo();
                    alertDialog.dismiss();
                    alertDialog = null;
                }
            });

            alertDialog = dl.create();
            alertDialog.show();
        }
    };

    /* the invitation to video call has be accepted. */
    private BroadcastReceiver callTypeChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CallSession session = (CallSession) intent.getSerializableExtra(CallApi.PARAM_CALL_SESSION);
            if (!callSession.equals(session)) {
                return;
            }
            int newType = intent.getIntExtra(CallApi.PARAM_NEW_TYPE, -1);
            if (newType == CallSession.TYPE_VIDEO) {
				/*Intent newIntent = new Intent(ACT_DemoCallTalking.this, ACT_DemoCallTalkingVideo.class);
				startActivity(newIntent);*/
                finish();
            }
        }
    };

    /* the invitation to video call has be rejected. */
    private BroadcastReceiver callTypeChangeRejectedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CallSession session = (CallSession) intent.getSerializableExtra(CallApi.PARAM_CALL_SESSION);
            if (!callSession.equals(session)) {
                return;
            }
            Toast.makeText(getApplicationContext(),
                    "You invitation is rejected", Toast.LENGTH_LONG).show();
        }
    };

    /* deal with qos report event. */
    private BroadcastReceiver callQosReportReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            CallSession session = (CallSession) intent.getSerializableExtra(CallApi.PARAM_CALL_SESSION);
            if (!callSession.equals(session)) {
                return;
            }
            int quality = intent.getIntExtra(CallApi.PARAM_CALL_QOS, CallApi.QOS_QUALITY_NORMAL);
            switch (quality) {
                case CallApi.QOS_QUALITY_GOOD:
                    txtNetworkQuality.setText("网络状况：良好");//网络状况：
                    break;

                case CallApi.QOS_QUALITY_NORMAL:
                    txtNetworkQuality.setText("网络状况：正常");
                    break;

                case CallApi.QOS_QUALITY_BAD:
                    txtNetworkQuality.setText("网络状况：差");
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
